<?php

namespace App\Library\Message\Channels;

use App\Components\System\Models\WeChatMessageSendResult;
use Illuminate\Notifications\Notification;

class WeChatTemplateChannel
{
    /**
     * @var \EasyWeChat\OfficialAccount\TemplateMessage\Client
     */
    private $template;

    public function __construct()
    {
        $this->template = app(\EasyWeChat\OfficialAccount\Application::class)->template_message;
    }

    public function send($notifiable, Notification $notification)
    {
        if (! $to = $notifiable->routeNotificationFor('we_chat', $notification)) {
            return;
        }

        $message = $notification->toWeChatTemplate($notifiable);

        if (is_null($message)) {
            return;
        }

        $templateId = config("services.wechat.template.{$message['template_id']}");

        if (is_null($templateId)) {
            return;
        }

        $result = $this->template->send([
            'touser' => $to,
            'template_id' => $templateId,
            'url' => $message['url'] ?? null,
            'data' => $message['data'],
        ]);

        WeChatMessageSendResult::create([
            'open_id' => $to,
            'message' => get_class($notification),
            'err_code' => $result->errcode,
            'err_msg' => $result->errmsg,
        ]);

        if (method_exists($notification, 'onSendFinished')) {
            $notification->onSendFinished('we_chat_template', $result);
        }
    }
}
